package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenRepository;
import com.lagou.edu.entity.TokenEntity;
import com.lagou.edu.exception.ServiceException;
import com.lagou.edu.service.code.CodeService;
import com.lagou.edu.service.user.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.transaction.Transactional;
import java.util.Objects;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TokenRepository tokenRepostory;

    @Reference
    private CodeService codeService;

    @Transactional
    public boolean register(String email, String password, String code) {
        int validate = codeService.validate(email, code);
        if (validate == 1) {
            throw new ServiceException("验证码不正确");
        }
        if (validate == 2) {
            throw new ServiceException("验证码已过期");
        }
        if (validate == 0){
            if (this.isRegistered(email)) {
                throw new ServiceException(email + " 已注册, 请勿重复注册");
            }
            tokenRepostory.save(TokenEntity.builder()
                .email(email)
                .token(UUID.randomUUID().toString())
                .build()
            );
            return true;
        }
        return false;
    }

    @Transactional
    public boolean isRegistered(String email) {
        return tokenRepostory.findByEmail(email) != null;
    }

    @Transactional
    public String login(String email, String password) {
        // 未存储密码，所以校验自动通过
        TokenEntity tokenEntity = tokenRepostory.findByEmail(email);
        if (tokenEntity != null){
            String token = UUID.randomUUID().toString();
            tokenEntity.setToken(token);
            tokenRepostory.save(tokenEntity);
            return token;
        }
        return null;
    }

    @Transactional
    public String info(String token) {
        TokenEntity byToken = tokenRepostory.findByToken(token);
        if (Objects.nonNull(byToken)){
            return byToken.getEmail();
        }
        return "";
    }
}
